﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class player_controller : MonoBehaviour
{
    public float run_speed;
    public float jump_speed;


    private Rigidbody2D my_rigidbody2d;
    private BoxCollider2D my_feet;
    private bool is_ground;

    private float playerGravity;

    void Start()
    {
        my_rigidbody2d = GetComponent<Rigidbody2D>();
        my_feet = GetComponent<BoxCollider2D>();
        playerGravity = my_rigidbody2d.gravityScale;
        //playerGravity = -18;

    }

    
    void Update()
    {
        Run();
        Jump();
        ground_check();
        Flip();
    }

    void ground_check()//检测是否是地面
    {
        is_ground =( my_feet.IsTouchingLayers(LayerMask.GetMask("ground")) || my_feet.IsTouchingLayers(LayerMask.GetMask("square")));
        //Debug.Log(is_ground);
    }
    void Run()
    {
        //左右移动
        float moveDir = Input.GetAxis("Horizontal");
        Vector2 player_vel = new Vector2(moveDir * run_speed, my_rigidbody2d.velocity.y);
        my_rigidbody2d.velocity = player_vel;

        //左右移动的动画
        bool playerHasXAxisSpeed = Mathf.Abs(my_rigidbody2d.velocity.x) > Mathf.Epsilon;
    }


    void Jump()
    {
        if (Input.GetButtonDown("Jump") && is_ground)
        {
            my_rigidbody2d.velocity = new Vector2(my_rigidbody2d.velocity.x, jump_speed);
            //Debug.Log("............");
        }
    }

    void Flip()
    {
        bool playerHasXAxisSpeed = Mathf.Abs(my_rigidbody2d.velocity.x) > Mathf.Epsilon;
        if (playerHasXAxisSpeed)
        {
            if (my_rigidbody2d.velocity.x > 0.1f)//0.1好一点嗷，判断方向是否往右
            {
                transform.localRotation = Quaternion.Euler(0, 0, 0);//不反转0.0.0
            }
            if (my_rigidbody2d.velocity.x < -0.1f)//判断方向是否往左
            {
                transform.localRotation = Quaternion.Euler(0, 180, 0);
            }
        }
    }
}
